package org.example.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    public static  String url;
    public static String DbUsername;
    public static String DbPassword;
    static {
        InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            url = properties.getProperty("url");
            DbUsername = properties.getProperty("dbUsername");
            DbPassword = properties.getProperty("dbPassword");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws  SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return  DriverManager.getConnection(url, DbUsername, DbPassword);
    }
    /**
     * 释放资源
     * @param statement
     * @param conn
     * @param resultSet
     * @throws SQLException
     */
    public static void close(Statement statement, Connection conn, ResultSet resultSet) {
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
